<?php
/**
-------------------------
GNU GPL COPYRIGHT NOTICES
-------------------------
This file is part of FlexicaCMS.

FlexicaCMS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

FlexicaCMS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with FlexicaCMS.  If not, see <http://www.gnu.org/licenses/>.*/

/**
 * $Id$
 *
 * @author FlexicaCMS team <contact@flexicacms.com>
 * @link http://www.flexicacms.com/
 * @copyright Copyright &copy; 2009-2010 Gia Han Online Solutions Ltd.
 * @license http://www.flexicacms.com/license.html
 */

/**
* Upload file using SwfUpload http://swfupload.org/
* After a file is uploaded successfully, the id of the file 
* which returned from server is stored in a hidden file named $fileIds
*/
class SwfUploadWidget extends CWidget
{
    // Path which stores images, js, styles, swf files
    // For exam, /themes/global/scripts/SwfUpload/
    public $resourcePath;
    
    // File post name
    public $filePostName = 'attachedFile';
    
    // Upload url
    public $uploadUrl;
    
    // Button image url
    public $buttonImageUrl;
    
    // Store file ids returned from server
    public $fileIdsHiddenFieldName = '';
    public $fileIdsHiddenFieldId = '';
    
    // File size limit
    public $fileSizeLimit = '5 MB';
    
    // File types
    public $fileTypes = '*.*';
    
    // File upload limit
    public $fileUploadLimit = 5;
    /*
    * Following is the properties which determine how the files are uploaded, which means immediately or waits until the form is validated successfully (using Jquery validation)
    */
    public $uploadType = "AfterFormValidation"; // "AfterFormValidation" or "Immediately"
    // The form to which this widget resides
    public $formId; // required only if $uploadType = "AfterFormValidation"
    
    // The submit button in a form (if any)
    public $submitButtonId; // required only if $uploadType = "AfterFormValidation"
    
    public function init()
    {
        parent::init();
    }
    
    private function registerClientScripts()
    {
        $this->resourcePath = rtrim($this->resourcePath, '/');
        $cs = Yii::app()->clientScript;
        
        // Register js files
        $cs->registerScriptFile($this->resourcePath.'/js/swfupload.js', CClientScript::POS_BEGIN);
        $cs->registerScriptFile($this->resourcePath.'/js/swfupload.queue.js', CClientScript::POS_BEGIN);
        $cs->registerScriptFile($this->resourcePath.'/js/handlers.js', CClientScript::POS_BEGIN);
        $cs->registerScriptFile($this->resourcePath.'/js/fileprogress.js', CClientScript::POS_BEGIN);
        
        // Register css files
        // You can edit css style in this file
        $cs->registerCssFile($this->resourcePath.'/styles/default.css'); 
    }
    //private function registerScriptFile
    public function run()
    {
        $this->registerClientScripts();
        $sessionId = session_id();
        
        $output = <<<EOP
        <div id="swfwrapper">
            <div>
                <span id="spanButtonPlaceHolder"></span>
                
                <input id="btnCancel" type="button" value="Cancel All Uploads" onclick="swfu.cancelQueue();" disabled="disabled" />
            </div>
            <div id="fsUploadProgress" class="fieldset flash">
                <span class="legend">Upload queue</span>
            </div>
            <div id="divStatus">0 Files Uploaded</div>
            <input type="hidden" name="{$this->fileIdsHiddenFieldName}" id="{$this->fileIdsHiddenFieldId}" value="" />
        </div>
        
<script type="text/javascript">
    var swfu;
    $().ready(
        function() {
            var settings = {
                flash_url : "{$this->resourcePath}/swfupload.swf",
                flash9_url : "{$this->resourcePath}/swfupload_fp9.swf",
                upload_url: "{$this->uploadUrl}",
                file_post_name: "{$this->filePostName}",
                post_params: {"PHPSESSID" : "{$sessionId}"},
                file_size_limit : "{$this->fileSizeLimit}",
                file_types : "{$this->fileTypes}",
                file_types_description : "All Files",
                file_upload_limit : {$this->fileUploadLimit},
                file_queue_limit : 0,
                custom_settings : {
                    progressTarget : "fsUploadProgress",
                    cancelButtonId : "btnCancel",
                    fileIds: "{$this->fileIdsHiddenFieldId}",
                    upload_successful : false
                },
                debug: false,

                // Button settings
                button_image_url: "{$this->buttonImageUrl}",
                button_width: "61",
                button_height: "22",
                button_placeholder_id: "spanButtonPlaceHolder",
                button_text: '',
                button_text_style: ".theFont { font-size: 16; }",
                button_text_left_padding: 12,
                button_text_top_padding: 3,
                
                // The event handler functions are defined in handlers.js
                swfupload_preload_handler : preLoad,
                swfupload_load_failed_handler : loadFailed,
                file_queued_handler : fileQueued,
                file_queue_error_handler : fileQueueError,
                file_dialog_complete_handler : fileDialogComplete,
                upload_start_handler : uploadStart,
                upload_progress_handler : uploadProgress,
                upload_error_handler : uploadError,
                upload_success_handler : uploadSuccess,
                upload_complete_handler : uploadComplete,
                queue_complete_handler : queueComplete    // Queue plugin event
            };

            swfu = new SWFUpload(settings);
         
     
     
     

EOP;
        if ($this->uploadType == "AfterFormValidation")
        {
            $output .= <<<EOP
       
       $("#{$this->submitButtonId}").click(function(e){
            if ($("#{$this->formId}").valid()){
                $("#{$this->submitButtonId}").attr("disabled", "disabled");
                $("#{$this->submitButtonId}").parent().append("<img src='{$this->resourcePath}/images/loading.gif' />");
                if (swfu.getStats().files_queued === 0)
                {
                    uploadDone();
                }
                else
                {
                    try {
                        swfu.startUpload();
                    } catch (ex) {
                        alert(ex);
                    }
                }
            }
            
            return false; //prevent the form from submitting, the form then will be submitted in the function uploadDone() which is called in uploadComplete() function
        }); 
        
        function fileDialogComplete(numFilesSelected, numFilesQueued) {
            try {
                if (numFilesSelected > 0) {
                    document.getElementById(this.customSettings.cancelButtonId).disabled = false;
                }
            } catch (ex)  {
                this.debug(ex);
            }
        }
EOP;
        }
        else
        {
            $output .= <<<EOP
        function fileDialogComplete(numFilesSelected, numFilesQueued) {
        try {
            if (numFilesSelected > 0) {
                document.getElementById(this.customSettings.cancelButtonId).disabled = false;
            }
            
            // I want auto start the upload and I can do that here
            swfu.startUpload();
        } catch (ex)  {
            this.debug(ex);
        }
}    
EOP;
        }
        
        $output .= <<<EOP
        } // of ready function
        ); // of $().ready()
</script>
EOP;

        echo $output;
    }
}
?>
